const amap = require("../../../util/amap");
// 获取当前时间
var currentTime = new Date();

// 判断上午或下午
var meridiem = currentTime.getHours() < 12 ? '上午' : '下午';

// 将当前时间格式化为你想要的格式，比如 yyyy-MM-dd HH:mm:ss
var year = currentTime.getFullYear();
var month = currentTime.getMonth() + 1;
var date = currentTime.getDate();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();

// 格式化时间，确保月、日、时、分、秒始终为两位数
if (month < 10) {
    month = '0' + month;
}
if (date < 10) {
    date = '0' + date;
}
if (hours < 10) {
    hours = '0' + hours;
}
if (minutes < 10) {
    minutes = '0' + minutes;
}
if (seconds < 10) {
    seconds = '0' + seconds;
}

// 将时间拼接成字符串，形如 "2024-03-11 14:30:00"
var time = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;




Page({
  data: {
    loadModal:'',
    user: '',
    result: '',
    result2: [],
    url_token: '',
    text: '',
    nearbyList: [], // 存储搜索到的景点信息
    markers: [], // 地图标记点
    polylines: [], // 地图路线
    latitude: 30.67, // 成都市中心点
    longitude: 104.06, // 成都市中心点
    feedback: '', 
    time:time,
    meridiem: meridiem,
    swiperList: [], // 轮播图列表
    nearbyCards: [], // 景点卡片列表
    currentSwiper: 0, // 当前轮播图索引
    DotStyle: false, // 轮播图指示点样式
    showRouteImage: false,
    routeImageUrl: '你的路线图片地址',
    showMap: false, // 添加控制地图显示的状态
  },
  onShow() {
    this.setData({ user: wx.getStorageSync('user') || '' });
   
  },
  onLoad: function(options) {
    this.setData({ user: wx.getStorageSync('user') || '' });
    this.getRecommendUrl();
    this.getLatestRecommendation();
  },
  getLatestRecommendation() {
    const db = wx.cloud.database();
    const user = this.data.user;
    console.log('用户名', user)
    db.collection('zyzl_recommandorder')
      .where({
        user: user
      })
      .orderBy('timestamp', 'desc')
      .limit(1)
      .get()
      .then(res => {
        console.log("res是",res);
        if (res.data.length > 0) {
          const latestData = res.data[0];
          const nearbyList = latestData.nearbyList;
          const result = decodeURIComponent(latestData.result.result);
          const formattedResult = this.formatResult(result);

          // 获取每个景点的详细信息
          const promises = nearbyList.map(item => {
            return db.collection('zyzl_nearbylist').doc(item._id).get();
          });

          Promise.all(promises).then(detailResults => {
            const nearbyDetails = detailResults.map(detail => detail.data);
            
            // 从 nearbyList 和 nearbyDetails 生成轮播图数据和卡片数据
            const swiperList = nearbyDetails.map(item => ({
              image: item.img1,
              id: item._id
            }));

            const nearbyCards = nearbyDetails.map(item => ({
              title: item.name,
              desc: item.desc,
              time: item.time,
              rating: 4,
              latitude2: item.latitude2,
              longitude2: item.longitude2,
              city: item.city
            }));

            this.setData({
              result: formattedResult,
              nearbyList: nearbyDetails,
              swiperList,
              nearbyCards,
              currentSwiper: 0
            });
            this.initMap();
          });
        } else {
          console.error('未找到最新的推荐订单数据');
          this.setData({
            result: '您还没有使用过智能推荐哦'
          });
        }
      })
      .catch(err => {
        console.error('获取最新数据失败', err);
      });
  },

  getToken2() {
    // 显示加载框
    this.setData({
      loadModal: true
    });

    wx.request({
      url: this.data.url_token,
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      success: res => {
        const access_token = res.data.access_token;
        const url_chat = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + access_token;
        
        // 构建二次推荐的请求
        const payload = {
          messages: [{
            role: "user",
            content: "这个推荐路线用户不满意：【" + this.data.result + "】，不满意的原因是：【" + this.data.feedback + "】，请优化这个结果并重新生成推荐结果" + "，格式要求参考：【" + this.data.text + "】"
          }]
        };

        // 获取新的推荐结果
        wx.request({
          url: url_chat,
          method: "POST",
          data: payload,
          header: { 'Content-Type': 'application/json' },
          success: res => {
            console.log("res是",res)
            if (res.data && res.data.result) {
              // 保存新的推荐结果
              const newResult = res.data.result;
              
              // 获取新推荐中的景点名称
              wx.request({
                url: url_chat,
                method: "POST",
                data: {
                  messages: [{
                    role: "user",
                    content: "提取下方推荐信息的所有景点名称并严格按照数组格式返回给我(格式参考： [\"天坛公园\", \"故宫\", \"颐和园\", \"北海公园\", \"圆明园\"]，提取到的景点名称必须放在[]里面)，需要提取景点名的推荐信息如下：" + newResult
                  }]
                },
                header: { 'Content-Type': 'application/json' },
                success: res => {
                  if (res.data && res.data.result) {
                    // 更新页面数据
                    this.setData({
                      result: this.formatResult(newResult),
                      result2: res.data.result,
                      loadModal: false
                    });

                    // 保存推荐记录
                    this.saveRecommendOrder({
                      result: newResult,
                      timestamp: new Date()
                    });

                    // 重新搜索景点信息
                    this.searchNearby();

                    wx.showToast({
                      title: '推荐成功',
                      icon: 'success'
                    });
                  } else {
                    this.handleError('解析景点失败');
                  }
                },
                fail: err => {
                  this.handleError('解析景点请求失败');
                }
              });
            } else {
              this.handleError('获取推荐失败');
            }
          },
          fail: err => {
            this.handleError('推荐请求失败');
          }
        });
      },
      fail: err => {
        this.handleError('获取token失败');
      }
    });
  },
    getRecommendUrl() {
      const db = wx.cloud.database();
      const recommendCollection = db.collection('zyzl_recommend');
      recommendCollection.get().then(res => {
        console.log("res1",res);
        if (res.data.length > 0) {
          const recommendInfo = res.data[0];
          const url_token = recommendInfo.url_token; // 获取recommend字段中的url_token值
          const text = recommendInfo.text;
          this.setData({ url_token }); // 设置到页面数据中
          this.setData({ text });
        } else {
          console.error('未找到数据');
        }
      }).catch(err => {
        console.error('获取数据失败', err);
      });
    },

    getClass: function(index) {
      var classArray = ['bg-green shadow-blur', 'bg-grey shadow-blur', 'bg-blue content', 'bg-cyan content']; // 定义不同的 class 数组
      return classArray[index % classArray.length]; // 返回对应索引的 class
    },
    saveRecommendOrder(result) {
      const db = wx.cloud.database();
      const orderCollection = db.collection('zyzl_recommandorder');
      const orderData = {
        user: this.data.user,
        result: result,
        timestamp: this.data.timestamp,
        feedback:this.data.feedback
      };
      orderCollection.add({
        data: orderData,
        success: res => {
          console.log('存储成功', res);
        },
        fail: err => {
          console.error('存储失败', err);
        }
      });
    },
    showFeedbackDialog() {
      wx.showModal({
        title: '反馈信息',
        editable:true,//显示输入框
        placeholderText:'请输入不满意的原因',//显示输入框提示信息             
        showCancel: true, // 显示取消按钮
        success: (modalRes) => {
          console.log("modalRes:",modalRes);
          if (modalRes.confirm) {
          
            this.setData({ feedback: modalRes.content });
            this.getToken2();

          } else {
            // 用户点击取消时，不执行任何操作
          }
        }
      });
    },

    initMap() {
      // 获取附近景点信息
      const nearbyList = this.data.nearbyList;


      // 初始化地图标记点
      const markers = nearbyList.map((item, index) => {
        return {
          iconPath: "../../map/images/Redmaker.png",
          id: index,
          latitude: item.latitude2,
          longitude: item.longitude2,
          width: 20,
          height: 20
        };
      });

      // 设置地图标记点
      this.setData({ markers });
     
      // 绘制地图路线
      this.drawRoute();
    },
    drawRoute() {
      const nearbyList = this.data.nearbyList;
      const polylines = []; // 存储所有路线
    
      const promises = [];
    
      for (let i = 0; i < nearbyList.length - 1; i++) {
        const origin = `${nearbyList[i].longitude2},${nearbyList[i].latitude2}`;
        const destination = `${nearbyList[i + 1].longitude2},${nearbyList[i + 1].latitude2}`;
    
        const promise = amap.getRoute(origin, destination, "getDrivingRoute")
          .then(route => {
            const points = route.paths[0].steps.reduce((acc, step) => {
              const polyline = step.polyline.split(';');
              return acc.concat(polyline.map(point => {
                const [longitude, latitude] = point.split(',');
                return { latitude: parseFloat(latitude), longitude: parseFloat(longitude) };
              }));
            }, []);
    
            polylines.push({
              points,
              color: "#0091ff",
              width: 6
            });
          })
          .catch(error => {
            console.error('绘制路线失败', error);
          });
    
        promises.push(promise);
      }
    
      Promise.all(promises)
        .then(() => {
          this.setData({
            polylines: polylines
          });
        })
        .catch(error => {
          console.error('Promise.all 失败', error);
        });
    },
    
    


    
    submitScore(score) {
      const db = wx.cloud.database();
      const _ = db.command;

      // 查询最新一条数据的_id
      db.collection('zyzl_recommandorder')
        .orderBy('timestamp', 'desc')
        .limit(1)
        .get()
        .then(res => {
          if (res.data.length > 0) {
            const latestId = res.data[0]._id;
            // 更新最新一条数据的评分字段和低分原因
            db.collection('zyzl_recommandorder')
              .doc(latestId)
              .update({
                data: {
                  score: score,
                  feedback: this.data.feedback // 将填写的低分原因一同提交
                }
              })
              .then(() => {
                wx.showToast({
                  title: '反馈成功',
                  icon: 'success'
                });
                if (score === 1 || score === 2) {
                  this.getToken2();
                }
              })
              .catch((err) => {
                wx.showToast({
                  title: '反馈失败',
                  icon: 'success'
                });
              });
          } else {
            console.error('未找到最新的推荐订单数据');
          }
        })
        .catch((err) => {
          console.error('查询最新数据失败', err);
        });
    },

    formatResult: function(result) {
      return result.replace(/\n/g, '<br>'); // 将换行符替换为 <br> 标签
    },

    // 轮播图切换事件
    swiperChange(e) {
      this.setData({
        currentSwiper: e.detail.current
      });
    },

    // 卡片切换事件
    cardChange(e) {
      this.setData({
        currentSwiper: e.detail.current
      });
    },

    // 预览图片
    previewImage(e) {
      const current = e.currentTarget.dataset.url;
      const urls = this.data.swiperList.map(item => item.image);
      wx.previewImage({
        current, // 当前显示图片的链接
        urls // 需要预览的图片链接列表
      });
    },

    // 显示地图
    showRouteImage() {
      this.setData({
        showMap: true
      });
    },

    // 隐藏地图
    hideRouteImage() {
      this.setData({
        showMap: false
      });
    },

    // 跳转到搜索页面
    goToSearch() {
      console.log(123);
      wx.navigateTo({
        url: '/miniprogram/pages/search/search'
      });
    },

    // 添加导航方法
    goToMap(e) {
      const index = e.currentTarget.dataset.index;
      const item = this.data.nearbyCards[index];
      
      wx.navigateTo({
        url: `/pages/map/routes/routes?latitude=${this.data.latitude}&longitude=${this.data.longitude}&latitude2=${item.latitude2}&longitude2=${item.longitude2}&city=${item.city}&name=${item.title}&desc=${item.desc}`
      });
    }
});
